import React, { Component, useMemo } from 'react'
import { View } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { SpNavBar } from '@/components'
import api from '@/api'
import './index.scss'
import { connect } from 'react-redux'
import ShopCheck from './comps/shopCheck' 
import {
    Form,
    Input,
    Button,
    ImageUploader,
    Dialog,
    TextArea,
    DatePicker,
    CascadePicker,
    Cascader,
    Stepper,
    Switch,
    Checkbox,
    Space,
    Radio,
    Selector,
    Picker,
    Popup,
    SearchBar,
    CheckList
} from 'antd-mobile'

import {
    SHOP_MAP,
    SELECCAT_MAP,
    BRAND_MAP2,
    GOOD_MAP
} from '../../../good/const'

@connect(({ planSelection }) => ({
    planSelection: planSelection.activeShop
}))
export default class List extends Component {
    formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            couponStr: '',
            items: [],
            shopItem: [],
            is_ziti: false,
            is_delivery: false,
            logo: [],
            banner: [],
            visible: false,
            defaultInfo: {},
            goodsList: [],
            form: {
                contact: '',
                regions: [],
                regions_id: [],
            },
        }
    }
    async componentWillUnmount() {
        console.log('2222')

    }
    // filteredItems = useMemo(() => {
    //     if (this.state.searchText) {
    //       return items.filter(item => item.includes(this.state.searchText))
    //     } else {
    //       return items
    //     }
    //   }, [items])
    async componentDidMount() {
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()

        await this.getAdressItem()
        if (!id) {
            this.setState({
                couponStr: '添加地址'
            })
        } else {
            this.setState({
                couponStr: '编辑地址'
            })
            // this.getShopDetail(id)
            const info = Taro.getStorageSync('addressInfo')
            info.regions_id = JSON.parse(info.regions_id)
            this.setState({
                defaultInfo:info
            })
            this.formRef.current?.setFieldsValue(info)
        }
        // const info = Taro.getStorageSync('addressInfo')
        // this.formRef.current?.setFieldsValue(info)
    }

    async componentDidShow() {
        console.log('dianwu h5 comonentDidShow...')

    }
    async getAdressItem() {
        const data = await api.address.areaList()
     this.setState({
            items: data
        })

    }
    async getShopDetail(id) {
        const form = await api.address.getAddressList({ 'distributor_id': id })

        this.formRef.current?.setFieldsValue(form)

    }
    onSubmit = async () => {
        const values = this.formRef.current?.getFieldsValue()
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })

        let params = this.state.form
        params = {
            ...params,
            ...JSON.parse(JSON.stringify(values)),

        }
        params.province = params.regions[0]
        params.city = params.regions[1]
        params.area = params.regions[2]
        params.regions_id = JSON.stringify(params.regions_id)
        params.regions = JSON.stringify(params.regions)
        params.distributor_id = JSON.stringify(params.distributor_id)
        console.log(params)
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        if (!id) {
            
            await api.address.postAddressList(params)
        } else {
            params.address_id = id
            params.distributor_id = this.state.defaultInfo.distributor_id 
            await api.address.updateAddressActive(params)
        }


        Taro.navigateBack()
    }
    onFinish = (values) => {
        console.log(values)
        if (values.quantity) {

        }
        this.onSubmit(values)
    }
    onFinishFailed = (values) => {
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })
    }
    onClickGoogs = async (values) => {
        console.log('index-294打印values', values)
        let list = this.getGood(values)
        console.log('index-294打印values', list)
        let lll = list.map((value) => {
            return value.value
        })
        this.state.shopItem = lll
     this.setState({
            goodsList: list,
            form: this.state.form
        })
      
        // params.items = lll
        this.formRef.current?.setFieldsValue({ distributor_id: lll })
    }
    getGood(value) {
        let list = this.transformData(value, SHOP_MAP)
        return list
    }
    transformData(data, obj) {
        let list = []
        data.forEach((item) => {
            let currentItem = {}
            for (let key in obj) {
                currentItem[obj[key]] = item[key]
            }
            if (item.children) {
                currentItem.children = transformData(item.children, obj)
            }
            list.push(currentItem)
        })
        return list
    }
    render() {
        const form = this.state.form
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        return (
            <View className='creat-form'>
                <SpNavBar title={this.state.couponStr} />
                <Form
                    ref={this.formRef}
                    layout='horizontal'
                    footer={
                        <Button block type='submit' color='primary' size='large' >
                            提交
                        </Button>
                    }
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    initialValues={{}}
                >

                    {!id ?(<Form.Item label="选择店铺" name='distributor_id'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '店铺不能为空' }]}
                        onClick={(e) => {
                            this.setState({
                                visible: true
                            })
                        }}
                    >
                        {/* <Input readOnly /> */}
                        <Selector
                            columns={2}
                            multiple
                            options={this.state.goodsList}
                            disabled
                        />
                    </Form.Item>):( <Form.Item
                        name='name'
                        label='店铺'

                        
                    >
                        <Input disabled></Input>
                    </Form.Item>)}
                   
                    <Form.Item
                        name='contact'
                        label='联系人姓名'
                        rules={[{
                            required: true,
                            message: '联系人姓名',
                        }]}
                    >
                        <Input onChange={console.log} placeholder='请输入联系人姓名' />
                    </Form.Item>

                    <Form.Item
                        name='mobile'
                        label='联系方式'
                        rules={[{
                            required: true,
                            message: '联系方式',
                            // pattern: '(^1[3-9]\\d{9}$)'
                        }]}
                    >
                        <Input onChange={console.log} placeholder='请输入联系方式' />
                    </Form.Item>

                    <Form.Item label="店铺地址" name='regions_id'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '请选择地址' }]}
                        onClick={(e, datePickerRef) => {
                            datePickerRef.current?.open() // ⬅️
                        }}
                    >
                        <Cascader
                            options={this.state.items}
                            value={this.state.form.regions_id}
                            onChange
                        >
                            {items => {
                                console.log(items)
                                if (items.every(item => item === null)) {
                                    return '未选择'
                                } else {
                                    this.state.form.regions = items.map(item => item?.label ?? '未选择')
                                    return items.map(item => item?.label ?? '未选择').join('-')
                                }
                            }}
                        </Cascader>
                    </Form.Item>
                    <Form.Item name='address' label='详细地址'
                        rules={[{ required: true, message: '详细地址不能为空' }]}>
                        <TextArea
                            placeholder='请填写详细地址'
                            maxLength={100}
                            showCount
                        />
                    </Form.Item>
                </Form>
                <Popup
                    position='right'
                    showCloseButton
                    visible={this.state.visible}
                    onMaskClick={() => {
                        this.setState({
                            visible: false
                        })
                    }}
                    destroyOnClose
                    onClose={() => {
                        this.setState({
                            visible: false,
                        })
                    }}
                >
                    <div className='rigth-btn' onClick={() => {
                        this.setState({
                            visible: false,
                        })
                    }}>
                        确定
                    </div>
                    <div className='popup-body'>
                        <div >
                            <ShopCheck onChange={this.onClickGoogs} selected={this.state.shopItem} value='1'></ShopCheck>
                        </div>
                    </div>
                </Popup>
            </View >

        )
    }
}
